<template>
  <el-dialog v-model="model" title="修改头像" width="30%">
    <div style="text-align: center;">
      <!-- 当前头像预览 -->
      <div style="margin-bottom: 15px;">头像预览：</div>
      <div class="avatar-preview">
        <img :src="previewAvatarUrl" alt="Current Avatar" @error="handlePreviewError"/>
      </div>

      <!-- 上传新头像 -->
      <el-upload
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleAvatarChange"
        accept="image/jpeg,image/png,image/gif,image/webp"
      >
        <el-button type="primary">选择图片</el-button>
      </el-upload>

      <!-- 提交按钮 -->
      <div style="margin-top: 15px;">
        <el-button type="success" @click="submitAvatar">确认修改</el-button>
      </div>
      <!-- 提示信息 -->
      <div style="margin-top: 10px; font-size: 12px; color: #999;">
        图片支持格式：JPG / PNG / GIF / WebP<br/>
        大小限制：不超过 2MB
    </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref,watch } from 'vue'
import { ElMessage } from 'element-plus'
import { defineModel,defineProps } from 'vue'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8080";
const model = defineModel()

const defaultImageUrl = new URL('../../assets/error2.png', import.meta.url).href;
const nullImageUrl = new URL('../../assets/noPicture.jpg', import.meta.url).href;
const handlePreviewError = (event) => {
  // 设置为默认图片
  event.target.src = nullImageUrl;
  console.log('头像预览加载失败，已替换为默认图');
};

// 新增：接收当前头像 URL
const props = defineProps({
  currentAvatar: {
    type: String,
    default: '' // 默认为空
  }
})
const previewAvatarUrl = ref(props.currentAvatar) // 预览头像 URL

watch(() => props.currentAvatar, (newVal) => {
  previewAvatarUrl.value = newVal // 更新 previewAvatarUrl
}, { immediate: true }) // immediate: true 确保初始化时也执行一次
const selectedFile = ref(null);

// 当对话框关闭时，重置预览和选中文件
watch(() => model.value, (visible) => {
  if (!visible) {
    previewAvatarUrl.value = props.currentAvatar // 恢复为原始头像
    selectedFile.value = null // 清空已选文件
  }
})

const handleAvatarChange = (file) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  const isValidType = allowedTypes.includes(file.raw.type);
  const isValidSize = file.raw.size / 1024 / 1024 < 2;

  if (!isValidType) {
    ElMessage.error('仅支持 JPG / PNG / GIF / WebP 格式的图片');
    return;
  }

  if (!isValidSize) {
    ElMessage.error('图片大小不能超过 2MB');
    return;
  }
  const reader = new FileReader();
  reader.onload = (e) => {
    previewAvatarUrl.value = e.target.result; // 更新预览头像
  };
  reader.readAsDataURL(file.raw);
  selectedFile.value = file.raw;
}

const emit = defineEmits(['confirm'])

const submitAvatar = async() => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择一张图片');
    return;
  }
  const formData = new FormData();
  formData.append('file', selectedFile.value);

  try {
    const token = sessionStorage.getItem('token');
    const response = await axios.post('/user/avatar', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `${token}`
      }
    });

    if (response.data.code === 0) {
      emit('confirm', response.data.data); // 传递头像 URL 到父组件
      dialogVisible.value = false;
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('头像上传失败');
  }
}
</script>
<style scoped>
.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #409EFF; /* 圆形边框颜色 */
  padding: 2px; /* 可选：让图片与边框之间有空隙 */
  background-color: #fff; /* 白色背景防止透明图干扰 */
  margin: 0 auto 15px auto;
  overflow: hidden;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}
</style>